﻿#region License

// Created by John Batte on 04/04/2012 at 5:34 AM.
// Last code cleanup: 04/04/2012 at 5:34 AM.
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#endregion

using System;

using BatteCode.Fx.ExceptionHandling;

namespace BatteCode.Fx.Reactive
{
	/// <summary>
	/// 	Provides extensions over the observer pattern.
	/// </summary>
	public static class ObserverExtensions
	{
		/// <summary>
		/// Pushes the item to the specified observer.
		/// </summary>
		/// <typeparam name="TItem">The type of the item.</typeparam>
		/// <param name="observer">The observer.</param>
		/// <param name="item">The item.</param>
		/// <param name="errorHandler">The error handler.</param>
		public static void PushNextResult<TItem>(this IObserver<TItem> observer, TItem item, Func<Exception, ExceptionState> errorHandler = null)
		{
			Func<Exception, ExceptionState> handler = errorHandler ?? Try.HandleErrors.DefaultStrategy;
			Try.Do(() => observer.OnNext(item), exception =>
			{
				observer.OnError(exception);
				return handler(exception);
			});
		}
	}
}